﻿@using Resource;
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <meta http-equiv="Expires" content="0">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Cache-control" content="no-cache">
    <meta http-equiv="Cache" content="no-cache">
    @{
        await Html.RenderPartialAsync("/Views/Shared/_LayoutScript.cshtml");
    }
    @{
        await Html.RenderPartialAsync("/Views/Shared/_StyleCss.cshtml");
    }

    <link href="/css/AssemblyDefect.css?v=@DateTime.Now.Ticks" rel="stylesheet" />
    <title>AssemblyDefect</title>
    <style type="text/css">
        /*报表样式*/
        html, body {
            background: url(../images/ProcessCapacity/bgwhite.png) no-repeat;
            background-size: cover;
            font-size: .16rem;
            color: #ffffff;
            position: relative;
            width: 100%;
            height: 100%;
            font-family: myFirstFont !important;
            color: black;
        }

        .hover-image {
            display: none;
            position: absolute;
            top: 20px;
            left: 0;
            width: 35vw;
            border: 1px solid #ccc;
            background: #fff;
            z-index: 999;
        }

        .warn-flag:hover .hover-image {
            display: block;
        }

        .rightTop {
            background-color: #f7fdff;
        }

        .dropbtn, button {
            background-color: #0aa9cd;
        }

        #query > button {
            background-color: #0aa9cd;
            border: 2px solid #0aa9cd;
        }

        .dropdown-content {
            background-color: #12bed0;
        }

        #defect_input {
            width: 100%;
            padding: 0.05rem;
            font-size: 0.14rem;
            padding: 0.032rem;
            border: 1px solid #0aa9cd;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            transition: border-color 0.3s ease-in-out, box-shadow 0.3s ease-in-out;
            outline: none;
        }

        #defect_input:focus {
            border-color: #007BFF;
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
        }

        .warn {
            background-color: #ffcccc;
        }

        .note {
            color: red;
            font-size: 0.15rem;
            font-weight: bolder;
        }

        .process:hover {
            background-color: #b3f1fe;
        }

        /*END*/
        .truncate {
            /*! max-width: 1.2rem; */
            white-space: nowrap;
            overflow: hidden;
            /*! text-overflow: ellipsis; */
        }

        /*明细模态*/
        .show_mode {
            border-radius: 0.1rem;
            position: absolute;
            z-index: 99;
            height: 10.6rem;
            width: 100%;
            /*text-align: center;*/
            background: #a2c2e2;
            display: none;
        }

        .show_mode > .contentdetail > div {
            color: black;
            height: 33.3%;
            width: 50%;
            float: left;
            border-block: solid #ffffff 1px;
        }

        .show_mode > .contentdetail > div > label {
            color: black;
        }

        .detail {
            color: black;
            background-color: #f7fdff;
            height: 3rem;
            width: 100%;
        }

        .mode_close {
            float: right;
        }

        .mode_close:hover {
            background-color: #848690;
        }
        /*end*/

        #left-table-body, #charttab1, #plato_chart {
            background-image: url('../images/loading.gif');
            background-size: 0.8rem 0.8rem;
            background-repeat: no-repeat;
            background-position: center;
        }

        th, td {
            padding: 0.05rem;
            border: 1px solid #0bc4e9;
        }

        .popup {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 95%;
            background-color: white;
            box-shadow: 0 0 10px rgba(4, 193, 250,1);
            border-radius: 8px;
        }

        .defect_close:hover {
            background-color: #d2e9f8;
        }

        #defect_detail > thead > tr {
            height: 0.3rem;
            background-color: #0bc4e9;
        }

    </style>
</head>
<body class="fill-parent" style="overflow-y: hidden; color: black;">
    <div class="main">
        <div class="header">
            <div class="header-left fl">
                <img src="/images/logo.png?v=@DateTime.Now.Ticks" class="scaled-image" draggable="false" oncontextmenu="return false;" ondragstart="return false;" />
            </div>
            <div class="btn">
                <spn>
                    <div id="query">
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Desktop</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" href=@Html.Raw($"https://dashboard.li.lumentuminc.net/API/DesktopApp/Dashboard.exe?v={DateTime.Now.Ticks}") download>@Label.Local</a>
                                <a class="menudropdown" href=@Html.Raw($"https://dashboard.li.lumentuminc.net/API/DesktopApp/Dashboard_lnk.zip?v={DateTime.Now.Ticks}") download>@Label.Shortcut</a>
                            </div>
                        </div>
                        <button class="dropbtn" onclick="DataToExport('VI_DefectReport')">@Label.Report@Label.Export</button>
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Language</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" onclick="setLanguageCookie('@Const.CNLANGUAGE')">@Label.Chinese</a>
                                <a class="menudropdown" onclick="setLanguageCookie('@Const.USLANGUAGE')">@Label.English</a>
                            </div>
                        </div>
                        <button class="modalBtn dimension">@Label.Full</button>
                    </div>
                </spn>
            </div>
            <div class="header-center fl">
                <div class="header-title"></div>
                <div class="header-img"></div>
            </div>
            <div class="header-right fl" id="time"></div>
            <div class="header-bottom fl"></div>
        </div>
        <div class="center">
            <div class="center-left fl">
                <div class="left-top rightTop border">
                    <div class="title note">
                        <span class="warn-flag" style="color:red; position: relative;">ℹ️<img src="../images/lot.png?v=@DateTime.Now.Ticks" class="hover-image" /></span>
                        @Label.Note_AssemblyDefect
                    </div>
                    <div id="board" style="padding: 0.2rem 0.2rem;">
                        <div class="query">
                            <input type="datetime-local" id="startdate" name="startdate" placeholder="@Label.Start@Label.Time" style="width:1.9rem">
                            <span class="exampleInputProject tle">@Label.To</span>
                            <input type="datetime-local" id="enddate" name="enddate" placeholder="@Label.Start@Label.End" style="width:1.9rem">
                            <select id="cmb_prod_type" name="ProdType" placeholder="select prodtype">
                                <option value="ALL">@Label.ALL</option>
                                <option value="Normal">@Label.Fresh</option>
                                <option value="Rework">@Label.Rework</option>
                                <option value="RMA">@Label.RMA</option>
                            </select>
                            <select id="cmb_proj_code" placeholder="select ProjCode">
                                <option value="ALL" selected>@Label.ALL</option>
                                <option value="">@Label.PleaseSelect</option>
                            </select>
                            <select id="cmb_product_code" placeholder="select ProductCode">
                                <option value="ALL" selected>@Label.ALL</option>
                                <option value="">@Label.PleaseSelect</option>
                            </select>
                            <select id="cmb_process" placeholder="select Process">
                                <option value="ALL" selected>@Label.ALL</option>
                                <option value="">@Label.PleaseSelect</option>
                            </select>
                            <select id="cmb_reporttype" placeholder="select Type">
                                <option value="Process" selected>By Process</option>
                                <option value="FailureMode">By FailureMode</option>
                            </select>
                            <button id="btn_query" class="btn btn-primary  btn-sm col-md-12" type="button" onclick="Getdata()">@Label.Query</button>
                        </div>
                        <div id="table-container">
                            <div id="left-table" class="rightTop">
                                <div id="left-table-body"></div>
                                <div class="popup">
                                    <span class="defect_close" style="font-size:0.15rem;color:red; float:right;font-weight:bold;" onclick="funclose()">关闭×</span>
                                    <div style="height:0.3rem">
                                        <span class="process_name" style="font-size:0.15rem;color:#007bff;font-weight:bold;line-height:0.3rem;padding-left: 0.15rem;"></span>
                                    </div>
                                    <div id="defect"></div>
                                </div>
                            </div>
                            <div id="right-table">
                                <div id="yield" class="rightTop">
                                    <div class="tab">
                                        <button class="tablinks active" onclick="OpenTab(event,'tab','charttab1',totalDefectfunction)">Total&nbsp;Defect&nbsp;Ratio&nbsp;Chart</button>
                                        <button class="tablinks" onclick="OpenTab(event,'tab','charttab1',defectByProcessfunction)">Defect&nbsp;By&nbsp;Process&nbsp;Ratio&nbsp;Chart</button>
                                        <button class="tablinks" onclick="OpenTab(event,'tab','charttab1',defectByfailuremodefunction)">VI&nbsp;FailureMode&nbsp;By&nbsp;Chart</button>
                                        <div style="float: right; line-height:0.5rem;">
                                            <select id="cmb_data_type">
                                                <option value="DAY">天</option>
                                                <option value="WEEK">周</option>
                                                <option value="MONTH">月</option>
                                            </select>
                                        </div>
                                        <div class="search" style="float: right; line-height:0.5rem;display:none;">
                                            <input list="defect_search" id="defect_input" name="search" placeholder="请输入Process...">
                                            <datalist id="defect_search" class="defect_search" style="height: calc(4.7rem - 0.12rem);"></datalist>
                                        </div>
                                    </div>
                                    <div id="charttab1" class="tabcontent"></div>
                                </div>
                                <div id="plato" class="rightTop">
                                    <div id="plato_chart"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="show_mode">
            <div style="width:100%; height:0.3rem;">
                <div class="mode_close" style="height:100%;margin-right:10px;line-height:0.3rem;">
                    <label style="font-size:0.17rem;color:white;">关闭&times;</label>
                </div>
            </div>
            <div class="contentdetail"></div>
        </div>
    </div>

    <script type="text/javascript" href="?v=@DateTime.Now.Ticks">
        $(".popup").css("display", "none");
        $(".search").css("display", "none");
        $(".show_mode").css("display", "none");
        $('.mode_close').click(function () {
            $(".show_mode").css("display", "none");
            $(".contentdetail").empty();
            $(".contentdetail div").remove();
        });
        $(document).ready(function () {
            var whei = $(window).height();
            $("html").css({ fontSize: whei / 12.5 });
            $(window).resize(function () {
                if ($(".dimension").text() == "@Html.Raw(Label.Full)") {
                    var whei = $(window).height();
                    $("html").css({ fontSize: whei / 12.5 });
                }
                else {
                    var whei = $(window).width();
                    $("html").css({ fontSize: whei / 22 });
                }
            });

            function numberToUpperCase(number) {
                var uppercaseMonths = [
                    '一月', '二月', '三月', '四月', '五月', '六月',
                    '七月', '八月', '九月', '十月', '十一月', '十二月'
                ];
                return uppercaseMonths[number - 1];
            }
            var myDate = new Date();
            var result = numberToUpperCase(myDate.getMonth() + 1);
            $('.header-title').html("@Html.Raw(Label.Board_AssemblyDefectReport)");
            function getTime() {
                var myDate = new Date();
                var myYear = myDate.getFullYear();
                var myMonth = myDate.getMonth() + 1;
                var myToday = myDate.getDate();
                var myDay = myDate.getDay();
                var myHour = myDate.getHours();
                var myMinute = myDate.getMinutes();
                var mySecond = myDate.getSeconds();
                var week = ['@Label.Sunday', '@Label.Monday', '@Label.Tuesday', '@Label.Wednesday', '@Label.Thursday', '@Label.Friday', '@Label.Saturday'];
                var nowTime;

                nowTime = myYear + '-' + fillZero(myMonth) + '-' + fillZero(myToday) + '&nbsp;&nbsp;' + fillZero(myHour) + ':' + fillZero(myMinute) + ':' + fillZero(mySecond) + '&nbsp;&nbsp;' + week[myDay] + '&nbsp;&nbsp;';
                $('#time').html(nowTime);
            };
            function fillZero(str) {
                var realNum;
                if (str < 10) {
                    realNum = '0' + str;
                } else {
                    realNum = str;
                }
                return realNum;
            }
            setInterval(getTime, 1000);
            $('.dimension').on('click', function (e) {
                var element = document.documentElement;
                if ($(".dimension").text() == "@Html.Raw(Label.Full)") {
                    if (element.requestFullscreen) {
                        element.requestFullscreen();
                    } else if (element.mozRequestFullScreen) {
                        element.mozRequestFullScreen();
                    } else if (element.webkitRequestFullscreen) {
                        element.webkitRequestFullscreen();
                    } else if (element.msRequestFullscreen) {
                        element.msRequestFullscreen();
                    }
                    $(".dimension").text("@Html.Raw(Label.Exit + Label.Full)");
                } else {
                    if (document.exitFullscreen) {
                        document.exitFullscreen();
                    } else if (document.mozCancelFullScreen) {
                        document.mozCancelFullScreen();
                    } else if (document.webkitCancelFullScreen) {
                        document.webkitCancelFullScreen();
                    } else if (document.msExitFullscreen) {
                        document.msExitFullscreen();
                    }
                    $(".dimension").text("@Html.Raw(Label.Full)");
                }
            });

            $('#btn_query').prop('disabled', true);
            $('#startdate').on('change', function () {
                var startDate = new Date($(this).val());
                var endDate = new Date($('#enddate').val());
                startDate.setDate(startDate.getDate() + 1);
                var minEndDate = startDate.toISOString().split('T')[0];
                $('#enddate').attr('min', minEndDate);
                if (endDate < startDate) {
                    $('#enddate').val($(this).val());
                }
            });
            $('#enddate').on('change', function () {
                var startDate = new Date($('#startdate').val());
                var endDate = new Date($(this).val());
                endDate.setDate(endDate.getDate() - 1);
                var maxStartDate = endDate.toISOString().split('T')[0];
                $('#startdate').attr('max', maxStartDate);
                if (startDate > endDate) {
                    $('#startdate').val($(this).val());
                }
            });

            var startDate = new Date();
            startDate.setDate(startDate.getDate() - 7);
            startDate.setHours(7, 0, 0, 0);
            var endDate = new Date();
            endDate.setDate(endDate.getDate() + 1);
            endDate.setHours(7, 0, 0, 0);
            var startdatetime = startDate.toLocaleDateString('sv-SE') + 'T' + startDate.toTimeString().slice(0, 5);
            $('#startdate').val(startdatetime);
            var enddatetime = endDate.toLocaleDateString('sv-SE') + 'T' + endDate.toTimeString().slice(0, 5);
            $('#enddate').val(enddatetime);
            ComboxAction();
            $('#cmb_proj_code').val('NCCSAD').trigger('change');
            $('#cmb_prod_type').val('ALL').trigger('change');
            $('#cmb_product_code').val('ALL').trigger('change');
            Getdata('ProcessByReport');
        });

        //定时查询
        var Tabtimer;
        function TabInterval() {
            clearInterval(Tabtimer);
            Tabtimer = setInterval(function () {
                var endDate = new Date($("#enddate").val());
                if (endDate > new Date()) {
                    getdate();
                }
            }, 10 * 60 * 1000);
        }

        /*Tab手动切换*/
        function OpenTab(evt, panle, id, echar_name, itemindex = -1) {
            $('#defect_input').val('ALL');
            $('#cmb_data_type').val('DAY');
            var i, tablinks;
            tablinks = document.getElementsByClassName(panle)[0].getElementsByClassName("tablinks");
            for (i = 0; i < tablinks.length; i++) {
                tablinks[i].className = tablinks[i].className.replace("active", "");
            }
            evt.currentTarget.className += " active";
            let chart = echarts.init(document.getElementById(id));
            chart.dispose();
            echar_name();
        }

        var productprocess;
        var ComboxAction = function () {
            var projectsele = $("#cmb_proj_code");
            var productcode = $("#cmb_product_code");
            var process = $("#cmb_process");
            var pam = {};
            var header_key = {
                start: $('#startdate').val(),
                end: $('#enddate').val()
            };
            loadData(projectsele, api + '/ReportAction/GetAssemblyProjCode', true);
            projectsele.change(function () {
                pam.proj_code = $(this).val();
                //pam.header_key = JSON.stringify(header_key);
                loadData(productcode, api + '/ReportAction/GetProductProcess', false);
            });
            productcode.change(function () {
                var processdt = productprocess.process.filter(item => item.product == $(this).val());
                Combox(processdt, process, false);
            });
            function loadData(selectElement, url, boolean) {
                $.ajax({
                    type: "POST",
                    url: url,
                    data: pam,
                    dataType: "json",
                    async: false,
                    success: function (data) {
                        if (url.includes("GetProductProcess")) {
                            selectdata = data.ReturnData.product;
                            productprocess = data.ReturnData;
                        }
                        else {
                            selectdata = data.ReturnData;
                        }
                        Combox(selectdata, selectElement, boolean);
                    }
                });
            }
            function Combox(selectdata, selectElement, boolean) {
                selectElement.empty();
                if (selectdata.length <= 0) {
                    @*selectElement.append("<option>@Html.Raw(Label.No + Label.Correlation + Label.Data)</option>");*@
                    selectElement.append("<option value='ALL'>@Html.Raw(Label.ALL)</option>");
                    return;
                }
                if (boolean) {
                    selectElement.append("<option value=''>@Html.Raw(Label.PleaseSelect)...</option>");
                } else {
                    selectElement.append("<option value='ALL'>@Html.Raw(Label.ALL)</option>");
                }
                $.each(selectdata, function (key, value) {
                    selectElement.append($('<option>', {
                        value: value.value,
                        text: value.text
                    }));
                });
            }
        }
        var Getdata = function () {
            getdate();
            TabInterval();
        }

        $(document).on('change', '#cmb_reporttype', function () {
            var type = $("#cmb_reporttype").val();
            if (type == "Process") {
                defectRatioBoarddata();
            }
            else {
                failuremodereport();
            }
        });

        //报表导出
        var ExportType;
        var DataToExport = function (type) {
            ExportType = type;
            var formData = new FormData();
            formData.append('start', $("#startdate").val());
            formData.append('end', $("#enddate").val());
            formData.append('prodtype', $('#cmb_prod_type').val());
            formData.append('proj_code', $('#cmb_proj_code').val());
            formData.append('product_code', $('#cmb_product_code').val());
            formData.append('process_id', $('#cmb_process').val() == null ? "ALL" : $('#cmb_process').val());
            formData.append('excelname', ExportType);
            var url = api + "/ReportAction/GetAssemblyDefectYieldToExcel";
            PostExportToExcel(url, formData);
            alert("数据量过大。。。\n\n正在加速下载，请等待2分钟^_^");
        }
        var PostExportToExcel = function (url, formData) {
            //GET: var url = "http://localhost:44304/Dashboard/ExportToExcel?" + $.param(pam);
            var xhr = new XMLHttpRequest();
            xhr.open('POST', url, true);
            xhr.responseType = 'blob';
            xhr.onload = function () {
                if (xhr.status === 200) {
                    var url = window.URL.createObjectURL(xhr.response);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = ExportType.toLocaleUpperCase() + '.xlsx';
                    a.click();
                    window.URL.revokeObjectURL(url);
                }
            };
            xhr.send(formData);
        }
        //导出
        var ExportToExcel = function (url) {
            //var url = "http://localhost:44304/Dashboard/ExportToExcel?" + $.param(pam);
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.responseType = 'blob';
            xhr.onload = function () {
                if (xhr.status === 200) {
                    var url = window.URL.createObjectURL(xhr.response);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = ExportType.toLocaleUpperCase() + '.xlsx';
                    a.click();
                    window.URL.revokeObjectURL(url);
                }
            };
            xhr.send();
        }
        //合并相同行
        function mergeFunc(tableId, maxCol) {
            var tab = document.getElementById(tableId);
            //var maxCol = 3;//maxcol用于设置需要合并的列数
            var count, start;
            for (var col = maxCol - 1; col >= 0; col--) {
                //用于存储相同个数
                count = 1;
                for (var i = 0; i < tab.rows.length; i++) {
                    if (i > 0 && col > 0 && tab.rows[i].cells[col].innerHTML == tab.rows[i - 1].cells[col].innerHTML
                        && tab.rows[i].cells[col - 1].innerHTML == tab.rows[i - 1].cells[col - 1].innerHTML) {
                        count++;
                    } else if (i > 0 && col == 0 && tab.rows[i].cells[col].innerHTML == tab.rows[i - 1].cells[col].innerHTML) {
                        count++;
                    } else {
                        if (count > 1) {
                            start = i - count;
                            tab.rows[start].cells[col].rowSpan = count;
                            for (var j = start + 1; j < i; j++) {
                                tab.rows[j].removeChild(tab.rows[j].cells[col]);
                            }
                            count = 1;
                        }
                    }
                }
                if (count > 1) { //合并，最后几行相同的情况下
                    start = i - count;
                    tab.rows[start].cells[col].rowSpan = count;
                    for (var j = start + 1; j < i; j++) {
                        tab.rows[j].removeChild(tab.rows[j].cells[col]);
                    }
                }
            }
        }

        function loadingshow() {
            $('#left-table-body,#charttab1,#plato_chart').css('background-image', 'url("../images/loading.gif")');
            $('#left-table-body,#charttab1,#plato_chart').css('background-size', '0.8rem 0.8rem');
            $('#left-table-body,#charttab1,#plato_chart').css('background-repeat', 'no-repeat');
            $('#left-table-body,#charttab1,#plato_chart').css('background-position', 'center');
        }
        function loadingnone() {
            $('#left-table-body,#charttab1,#plato_chart').css('background-image', 'none');
        }

        //获取数据
        var Tab;
        var getdate = function () {
            $(".popup").css("display", "none");
            $('#cmb_data_type').val('DAY');
            $('#cmb_reporttype').val('Process');
            $('#btn_query').prop('disabled', true);
            var header_key = {
                start: $('#startdate').val(),
                end: $('#enddate').val(),
                prodtype: $('#cmb_prod_type').val()
            };
            var pam = {};
            pam.proj_code = $('#cmb_proj_code').val();
            pam.product_code = $('#cmb_product_code').val();
            pam.process_id = $('#cmb_process').val();
            pam.header_key = JSON.stringify(header_key);
            if (pam.proj_code !== "-1") {
                loadingshow()
                $("#left-table-body").empty();
                $.ajax({
                    type: "POST",
                    url: api + "/ReportAction/GetAssemblyDefectYield",
                    data: pam,
                    dataType: "json",
                    success: function (dt) {
                        $('#btn_query').prop('disabled', false);
                        loadingnone();
                        Tab = dt.ReturnData;
                        defectSearchBinding();
                        defectRatioBoarddata();
                        totalDefectfunction();
                        //defectByProcessfunction()
                        platofunction();
                    }
                });
            }
        }

        //公共表格创建函数
        function createTable(config) {
            const { tableData, tableId, mergeConfig, footerValueMap, colspan = 3 } = config;
            $('#btn_query').prop('disabled', false);
            const $container = $("#left-table-body").empty().html(`
                <table id="${tableId}" class="DataSheet" border="1" style="width: 100%; height: 100%;">
                    <thead><tr></tr></thead>
                    <tbody></tbody>
                    <tfoot><tr></tr></tfoot>
                </table>
            `);
            const $table = $container.find(`#${tableId}`);
            const $theadTr = $table.find('thead tr');
            const $tbody = $table.find('tbody');
            const $tfootTr = $table.find('tfoot tr');
            const headers = Object.keys(tableData[0]);
            //创建表头
            headers.forEach(header => $theadTr.append(`<th>${header}</th>`));
            //处理表格数据行
            const formatNumber = (value, header) => {
                if (typeof value !== 'number') return value;
                return header === 'VI_DEFECT_RATIO'
                    ? `${parseFloat(value).toFixed(3)}%`
                    : value.toFixed(0);
            };
            const rows = tableData.map(row => {
                const cells = headers.map(header => {
                    const value = formatNumber(row[header], header);
                    const isProcess = header === 'PROCESS';
                    const isDefectQty = header === 'VI_DEFECT_QTY';
                    const isTotalDefectQty = header === 'TOTAL_DEFECT_QTY';

                    let cellContent = value;
                    if (isProcess || isDefectQty || isTotalDefectQty) {
                        const component = row['COMPONENT'];
                        const process = row['PROCESS'];
                        const boolFlag = isTotalDefectQty ? 'true' : 'false';
                        const clickHandler = isProcess
                            ? `process_select('${component}', '${process}')`
                            : `defect_detail('${component}', '${process}', ${boolFlag})`;
                        cellContent = `<a style="color:blue;font-weight:bolder;display:block;" onclick="${clickHandler}">${value}</a>`;
                    }
                    const className = isProcess || isDefectQty || isTotalDefectQty
                        ? 'truncate process'
                        : 'truncate';
                    return `<td class="${className}">${cellContent}</td>`;
                });
                return `<tr>${cells.join('')}</tr>`;
            });

            $tbody.html(rows.join(''));
            //创建表脚
            $tfootTr.html(`
                <th colspan="${colspan}">Total工序不良率</th>
                ${headers.slice(colspan).map(header => {
                const value = footerValueMap[header] ?? '';
                return `<th>${value}</th>`;
            }).join('')}
            `);
            //合并单元格处理
            if (mergeConfig) {
                mergeConfig.tableId && mergeFunc(mergeConfig.tableId, mergeConfig.columnIndex);
            }
        }

        //defectRatioBoarddata
        const defectRatioBoarddata = () => {
            var data = Tab.Table.map(item => {
                let newItem = Object.assign({}, item);
                delete newItem.PRODUCT_SEQ;
                delete newItem.PROCESS_SEQ;
                return newItem;
            });
            const calculateTotal = key => data.reduce((sum, item) =>
                sum + (parseFloat(item[key]) || 0), 0);
            const inputQty = calculateTotal("INPUT_QTY");
            const viDefectQty = calculateTotal("VI_DEFECT_QTY");
            const defectRatio = (viDefectQty / inputQty * 100).toFixed(3) + '%';
            createTable({
                tableData: data,
                tableId: 'defectTable',
                footerValueMap: {
                    INPUT_QTY: calculateTotal("INPUT_QTY"),
                    OUTPUT_QTY: calculateTotal("OUTPUT_QTY"),
                    TOTAL_DEFECT_QTY: calculateTotal("TOTAL_DEFECT_QTY"),
                    VI_DEFECT_QTY: viDefectQty,
                    VI_DEFECT_RATIO: defectRatio,
                    DPPM: (viDefectQty / inputQty * 1e6).toFixed(0)
                }
            });
        };

        //failuremodereport
        const failuremodereport = () => {
            const seen = new Set();
            var mergeData = Tab.Table1
                .filter(({ COMPONENT, PROCESS }) => {
                    const key = `${COMPONENT}_${PROCESS}`;
                    return seen.has(key) ? false : seen.add(key);
                })
                .map(({ PROJ_CODE, COMPONENT, PROCESS, INPUT_QTY, OUTPUT_QTY, TOTAL_DEFECT_QTY }) =>
                    ({ PROJ_CODE, COMPONENT, PROCESS, INPUT_QTY, OUTPUT_QTY, TOTAL_DEFECT_QTY })
                );
            const distinctTotal = key => mergeData.reduce((sum, item) =>
                sum + (parseFloat(item[key]) || 0), 0);
            const inputQty = distinctTotal("INPUT_QTY");
            const outputQty = distinctTotal("OUTPUT_QTY");
            const totaldefect = distinctTotal("TOTAL_DEFECT_QTY");

            const data = Tab.Table1;
            const calculateTotal = key => data.reduce((sum, item) =>
                sum + (parseFloat(item[key]) || 0), 0);
            const viDefectQty = calculateTotal("VI_DEFECT_QTY");
            const defectRatio = (viDefectQty / inputQty * 100).toFixed(3) + '%';
            createTable({
                tableData: data,
                tableId: 'failureTable',
                colspan: 3,
                footerValueMap: {
                    INPUT_QTY: inputQty,
                    OUTPUT_QTY: outputQty,
                    TOTAL_DEFECT_QTY:totaldefect,
                    DEFECT: '', //空值处理
                    VI_DEFECT_QTY: viDefectQty,
                    VI_DEFECT_RATIO: defectRatio,
                    DPPM: (viDefectQty / inputQty * 1e6).toFixed(0)
                },
                mergeConfig: {
                    tableId: "failureTable",
                    columnIndex: 6
                }
            });
        };

        //totalDefect
        var totalDefectChar;
        var totalDefectfunction = function () {
            tablinksonclick("totalDefect");
            var chartData = JSON.parse(Tab.Table5[0].TOTAL_DEFECT_DAY_JSON);
            var chartDom = document.getElementById("charttab1");
            if (chartDom) {
                echarts.dispose(chartDom);
            }
            totalDefectChar = echarts.init(chartDom);
            updatetotalDefectChartOptions(chartData, null);
        };
        var updatetotalDefectChartOptions = function (chartData, dataZoomConfig) {
            var dates = chartData.map(item => item.DATE);
            var viDefectRatios = chartData.map(item => item.VI_DEFECT_RATIO);
            //Top10
            var top10Indices = viDefectRatios.map((value, index) => ({ value, index })).sort((a, b) => b.value - a.value).slice(0, 10).map(item => item.index);
            var option = {
                textStyle: {
                    fontSize: '0.16rem'
                },
                tooltip: {
                    show: true,
                    trigger: 'axis',
                    textStyle: {
                        fontSize: '0.14rem'
                    },
                    axisPointer: {
                        type: 'cross',
                    },
                    formatter: function (params) {
                        let tooltipText = `<div>${params[0].axisValue}</div><table>`;
                        params.forEach(function (item) {
                            let dataItem = chartData.find(data => data.DATE == item.axisValue);
                            if (dataItem) {
                                tooltipText += `
                                <tr>
                                    <td>${item.marker}${item.seriesName}</td>
                                    <td>INPUT: ${dataItem.INPUT_QTY}</td>
                                    <td>OUTPUT: ${dataItem.OUTPUT_QTY}</td>
                                    <td>DEFECT: ${dataItem.DEFECT_QTY}</td>
                                    <td>VI_DEFECT: ${dataItem.VI_DEFECT_QTY}</td>
                                    <td>VI_DEFECT_RATIO: ${dataItem.VI_DEFECT_RATIO}%</td>
                                    <td>DPPM: ${dataItem.DPPM}</td>
                                </tr>`;
                            }
                        });
                        tooltipText += '</table>';
                        return tooltipText;
                    }
                },
                legend: {
                    show: true,
                    type: 'scroll',
                    width: '100%',
                    itemWidth: 10,
                    itemHeight: 10,
                    data: ['VI_DEFECT_RATIO'],
                    textStyle: {
                        fontSize: '0.16rem'
                    }
                },
                grid: {
                    top: '20%',
                    left: '8%',
                    right: '2%',
                    bottom: '10%',
                    width: '88%',
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: dates,
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: true
                    },
                    axisLabel: {
                        show: true,
                        textStyle: {
                            fontSize: '0.14rem'
                        }
                    }
                },
                yAxis: {
                    type: 'value',
                    name: 'TotalRatio(%)',
                    position: 'left',
                    nameTextStyle: {
                        fontSize: '0.14rem',
                        fontWeight: 'bold'
                    },
                    scale: true,
                    axisTick: {
                        show: true
                    },
                    axisLabel: {
                        show: true,
                        formatter: '{value}%',
                        textStyle: {
                            fontSize: '0.14rem'
                        }
                    }
                },
                series: [{
                    name: 'VI_DEFECT_RATIO',
                    type: 'line',
                    data: viDefectRatios,
                    smooth: false,
                    lineStyle: {
                        width: 2,
                        color: '#FF4500'
                    },
                    itemStyle: {
                        color: '#FF4500',
                        borderColor: '#FFF',
                        borderWidth: 2,
                        shadowBlur: 5,
                        shadowColor: 'rgba(255, 69, 0, 0.5)'
                    },
                    symbolSize: function (value, params) {
                        return top10Indices.includes(params.dataIndex) ? 8 : 0;
                    },
                    label: {
                        show: true,
                        position: 'top',
                        color: '#FFF',
                        fontSize: '0.14rem',
                        distance: 5,
                        backgroundColor: 'rgba(255, 69, 0, 0.8)',
                        borderRadius: 4,
                        padding: [2, 4],
                        textShadowColor: 'rgba(0, 0, 0, 0.5)',
                        textShadowBlur: 2,
                        formatter: function (params) {
                            return `${params.value.toFixed(3)}%`;
                        }
                    },
                    areaStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: 'rgba(255, 69, 0, 0.5)' },
                            { offset: 1, color: 'rgba(255, 69, 0, 0)' }
                        ])
                    },
                    tooltip: {
                        valueFormatter: function (value) {
                            return `${value.toFixed(3)}%`;
                        }
                    }
                }],
                dataZoom: dataZoomConfig
            };
            totalDefectChar.setOption(option, true);
        };

        //defectByProcess
        var defectByProcessChar;
        var defectByProcessfunction = function () {
            $(".search").css("display", "block");
            tablinksonclick("defectByProcess");
            var chartData = JSON.parse(Tab.Table4[0].DEFECT_RATIO_DAY_JSON);
            var chartDom = document.getElementById("charttab1");
            if (chartDom) {
                echarts.dispose(chartDom);
            }
            defectByProcessChar = echarts.init(chartDom);
            updatedefectByProcessChartOptions(chartData, null);
        };
        var updatedefectByProcessChartOptions = function (chartData, dataZoomConfig) {
            var groupedData = {};
            chartData.forEach(function (item) {
                if (!groupedData[item.PROCESS]) {
                    groupedData[item.PROCESS] = {};
                }
                groupedData[item.PROCESS][item.DATE] = item.VI_DEFECT_RATIO;
            });
            var uniqueTestTimes = chartData.map(item => item.DATE).filter((value, index, self) => self.indexOf(value) === index);
            var seriesData = Object.keys(groupedData).map(function (process) {
                var failData = uniqueTestTimes.map(function (time) {
                    return groupedData[process][time] || 0;
                });
                return {
                    name: process,
                    type: 'line',
                    data: failData
                };
            });
            var option = {
                textStyle: {
                    fontSize: '0.16rem'
                },
                tooltip: {
                    show: true,
                    trigger: 'axis',
                    textStyle: {
                        fontSize: '0.14rem'
                    },
                    axisPointer: {
                        type: 'cross',
                    },
                    formatter: function (params) {
                        let sortedParams = params.slice().sort((a, b) => b.data - a.data);
                        let tooltipText = `<div>${params[0].axisValue}</div><table>`;
                        let td = '';
                        let index = 0;
                        sortedParams.forEach(item => {
                            let dataItem = chartData.find(
                                data => data.DATE == item.axisValue && data.PROCESS == item.seriesName
                            );
                            if (dataItem && dataItem.VI_DEFECT_RATIO > 0) {
                                td += `
                                <td>${item.marker}${item.seriesName}</td>
                                <td>INPUT: ${dataItem.INPUT_QTY}</td>
                                <td>VI_DEFECT: ${dataItem.VI_DEFECT_QTY}</td>
                                <td>VI_DEFECT_RATIO: ${dataItem.VI_DEFECT_RATIO}%</td>`;
                                index++;
                                if (index % 2 == 0 || index == sortedParams.length) {
                                    tooltipText += `<tr>${td}</tr>`;
                                    td = '';
                                }
                            }
                        });
                        tooltipText += '</table>';
                        return tooltipText;
                    }
                },
                legend: {
                    show: true,
                    type: 'scroll',
                    width: '100%',
                    data: Object.keys(groupedData),
                    orient: 'horizontal',
                    itemWidth: 12,
                    itemHeight: 12,
                    scrollDataIndex: 0,
                    pageIconSize: [16, 16],
                    pageIconColor: '#0aa9cd',
                    pageTextStyle: {
                        fontSize: '0.16rem',
                    },
                    textStyle: {
                        fontSize: '0.16rem'
                    }
                },
                grid: {
                    top: '20%',
                    left: '8%',
                    right: '2%',
                    bottom: '10%',
                    width: '88%',
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: uniqueTestTimes,
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: true
                    },
                    axisLabel: {
                        textStyle: {
                            fontSize: '0.14rem'
                        },
                        show: true
                    }
                },
                yAxis: {
                    type: 'value',
                    name: 'DefectRatio(%)',
                    position: 'left',
                    nameTextStyle: {
                        fontSize: '0.14rem',
                        fontWeight: 'bold'
                    },
                    scale: true,
                    axisTick: {
                        show: true
                    },
                    axisLabel: {
                        formatter: function (value) {
                            return value + '%';
                        },
                        textStyle: {
                            fontSize: '0.14rem'
                        },
                        show: true
                    }
                },
                series: seriesData,
                dataZoom: dataZoomConfig
            };
            defectByProcessChar.setOption(option, true);
        };

        //defect绑定
        var defectSearchBinding = function () {
            var defectSearch = $('#defect_search');
            defectSearch.empty();
            var DefectSet = new Set();
            $.each(Tab.Table, function (index, item) {
                var PROCESS = item.PROCESS.trim();
                DefectSet.add(PROCESS);
            });
            defectSearch.append($('<option>').val('ALL'));
            DefectSet.forEach(function (PROCESS) {
                defectSearch.append($('<option>').val(PROCESS));
            });
            $('#defect_input').val('ALL');
        }

        var tablinksonclick = function (switch_on) {
            $('#cmb_data_type').val('DAY');
            var i, tablinks;
            tablinks = document.getElementsByClassName('tab')[0].getElementsByClassName("tablinks");
            for (i = 0; i < tablinks.length; i++) {
                tablinks[i].className = tablinks[i].className.replace("active", "");
                //console.log(tablinks[0].className.includes("active"));
            }
            switch (switch_on) {
                case "totalDefect":
                    tablinks[0].className += " active";
                    $(".search").css("display", "none");
                    break;
                case "defectByProcess":
                    tablinks[1].className += " active";
                    $(".search").css("display", "block");
                    break;
                case "defectByFailureMode":
                    tablinks[2].className += " active";
                    $(".search").css("display", "none");
                    break;
            }
        }

        function funclose (){
            $(".popup").css("display", "none");
            $("#defect").empty();
        }
        //sn_defect
        function defect_detail(product, process_id, boolflag) {
            $(".process_name").text(`工序：${process_id}`);
            $(".popup").css("display", "none");
            $("#defect").empty();
            var data = Tab.Table2
                .filter(item => item.INPUT_QTY !== item.OUTPUT_QTY && item.DEFECT !== null && item.COMPONENT === product && item.PROCESS === process_id && (boolflag || item.VI_DEFECT !== null))
                .map(item => {
                    let newItem = Object.assign({}, item);
                    delete newItem.JOB_NUM;
                    delete newItem.PART_NO;
                    delete newItem.PROJ_CODE;
                    delete newItem.COMPONENT;
                    delete newItem.PROCESS;
                    delete newItem.DEFECT_CODE;
                    delete newItem.VI_DEFECT_CODE;
                    delete newItem.VI_DEFECT;
                    return newItem;
                });
            if (data.length>0){
                $(".popup").css("display", "block");
                var defect_table_html = `
                <table id="defect_detail" style="margin: 0rem 0.15rem 0.15rem 0.15rem;width: calc(100% - 0.3rem);">
                    <thead><tr></tr></thead>
                    <tbody></tbody>
                </table>`;
                $("#defect").append(defect_table_html);
                var table = $('#defect_detail');
                var tbody = table.find('tbody');
                var headerRow = table.find('thead tr');
                var headers = Object.keys(data[0]);
                headers.forEach(function (header) {
                    headerRow.append('<th>' + header + '</th>');
                });
                var braNo = "style='text-align:center;background-color:#ffffff;'";
                var braTo = "style='text-align:center;background-color:#d2e9f8;'";
                data.forEach(function (row, index) {
                    index++;
                    var newRow = $(`<tr></tr>`);
                    var style = (index % 2) > 0 ? braNo : braTo;
                    headers.forEach(function (header, columnindex) {
                        if (header === "TEST_TIME") {
                            row[header] = row[header].replace("T"," ");
                        }
                        newRow.append(`<td ${style} class="truncate">${row[header]}</td>`);
                    });
                    tbody.append(newRow);
                });
            }
            if (data.length>25)
            {
                $("#defect").css("height", "7rem");
                $("#defect").css("overflow-y", "auto");
            }else{
                $("#defect").css("height", "50%");
            }
        }

        //defectByfailuremodefunction
        var defectByFailureModeChart
        var defectByfailuremodefunction =function(){
            $(".search").css("display", "block");
            tablinksonclick("defectByFailureMode");
            var chartData = JSON.parse(Tab.Table6[0].FAILURE_MODE_DAY_JSON);
            var chartDom = document.getElementById("charttab1");
            if (chartDom) {
                echarts.dispose(chartDom);
            }
            defectByFailureModeChart = echarts.init(chartDom);
            updatedefectByFailureModeChartOptions(chartData, null);
        }
        var updatedefectByFailureModeChartOptions = function (chartData, dataZoomConfig) {
            var groupedData = {};
            chartData.forEach(function (item) {
                if (!groupedData[item.DEFECT]) {
                    groupedData[item.DEFECT] = {};
                }
                groupedData[item.DEFECT][item.DATE] = item.VI_DEFECT_RATIO;
            });
            var uniqueTestTimes = chartData.map(item => item.DATE).filter((value, index, self) => self.indexOf(value) === index);
            var seriesData = Object.keys(groupedData).map(function (defect) {
                var failData = uniqueTestTimes.map(function (time) {
                    return groupedData[defect][time] || 0;
                });
                return {
                    name: defect,
                    type: 'line',
                    data: failData
                };
            });
            var option = {
                textStyle: {
                    fontSize: '0.16rem'
                },
                tooltip: {
                    show: true,
                    trigger: 'axis',
                    textStyle: {
                        fontSize: '0.14rem'
                    },
                    axisPointer: {
                        type: 'cross',
                    },
                    formatter: function (params) {
                        let sortedParams = params.slice().sort((a, b) => b.data - a.data);
                        let tooltipText = `<div>${params[0].axisValue}</div><table>`;
                        let td = '';
                        let index = 0;
                        sortedParams.forEach(item => {
                            let dataItem = chartData.find(
                                data => data.DATE == item.axisValue && data.DEFECT == item.seriesName
                            );
                            if (dataItem && dataItem.VI_DEFECT_RATIO > 0) {
                                td += `
                                <td>${item.marker}${item.seriesName}</td>
                                <td>INPUT: ${dataItem.INPUT_QTY}</td>
                                <td>VI_DEFECT: ${dataItem.VI_DEFECT_QTY}</td>
                                <td>VI_DEFECT_RATIO: ${dataItem.VI_DEFECT_RATIO}%</td>`;
                                index++;
                                if (index % 2 == 0 || index == sortedParams.length) {
                                    tooltipText += `<tr>${td}</tr>`;
                                    td = '';
                                }
                            }
                        });
                        tooltipText += '</table>';
                        return tooltipText;
                    }
                },
                legend: {
                    show: true,
                    type: 'scroll',
                    width: '100%',
                    data: Object.keys(groupedData),
                    orient: 'horizontal',
                    itemWidth: 12,
                    itemHeight: 12,
                    scrollDataIndex: 0,
                    pageIconSize: [16, 16],
                    pageIconColor: '#0aa9cd',
                    pageTextStyle: {
                        fontSize: '0.16rem',
                    },
                    textStyle: {
                        fontSize: '0.16rem'
                    }
                },
                grid: {
                    top: '20%',
                    left: '8%',
                    right: '2%',
                    bottom: '10%',
                    width: '88%',
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: uniqueTestTimes,
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: true
                    },
                    axisLabel: {
                        textStyle: {
                            fontSize: '0.14rem'
                        },
                        show: true
                    }
                },
                yAxis: {
                    type: 'value',
                    name: 'DefectRatio(%)',
                    position: 'left',
                    nameTextStyle: {
                        fontSize: '0.14rem',
                        fontWeight: 'bold'
                    },
                    scale: true,
                    axisTick: {
                        show: true
                    },
                    axisLabel: {
                        formatter: function (value) {
                            return value + '%';
                        },
                        textStyle: {
                            fontSize: '0.14rem'
                        },
                        show: true
                    }
                },
                series: seriesData,
                dataZoom: dataZoomConfig
            };
            defectByFailureModeChart.setOption(option, true);
        };

        //柏拉图
        var platoChar;
        var platooptionloop;
        var platofunction = function () {
            const group = {};
            Tab.Table3.forEach(item => {
                const defect = item.DEFECT;
                const qty = parseInt(item.DEFECT_QTY, 10);
                if (group[defect]) {
                    group[defect] += qty;
                } else {
                    group[defect] = qty;
                }
            });
            const chartData = Object.keys(group).map(defect => ({
                DEFECT: defect,
                DEFECT_QTY: group[defect]
            }));
            var DEFECTs = chartData.map(item => item.DEFECT);
            var DEFECT_QTY = chartData.map(item => parseFloat(item.DEFECT_QTY));
            var totalDefect_QTY = DEFECT_QTY.reduce((a, b) => a + b, 0);
            var cumulativeYield = [];
            var cumulativeSum = 0;
            DEFECT_QTY.forEach(function (value) {
                cumulativeSum += value;
                cumulativeYield.push(parseFloat((cumulativeSum / totalDefect_QTY * 100).toFixed(2)));
            });
            var chartDom = document.getElementById("plato_chart");
            if (chartDom) {
                echarts.dispose(chartDom);
            }
            platoChar = echarts.init(chartDom);
            var option = {
                title: {
                    text: 'Defect Pareto',
                    textStyle: {
                        fontSize: '0.16rem',
                        color: '#0aa9cd'
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross'
                    }
                },
                grid: {
                    top: '15%',
                    left: '5%',
                    right: '5%',
                    bottom: '20%',
                    width: '88%',
                },
                xAxis: {
                    type: 'category',
                    data: DEFECTs,
                    textStyle: {
                        fontSize: '0.14rem'
                    },
                    axisLabel: {
                        interval: DEFECTs.length >= 50 ? Math.ceil(DEFECTs.length / 50) : 0,
                        rotate: 45,
                        textStyle: {
                            fontSize: '0.14rem'
                        }
                    }
                },
                yAxis: [
                    {
                        type: 'value',
                        name: ' Defect Qty',
                        position: 'left',
                        nameTextStyle: {
                            fontSize: '0.14rem',
                            fontWeight: 'bold'
                        },
                        axisLine: {
                            show: false
                        },
                        axisTick: {
                            show: true
                        },
                        axisLabel: {
                            textStyle: {
                                fontSize: '0.14rem'
                            },
                            show: true
                        },
                        splitLine: {
                            show: false
                        }
                    },
                    {
                        type: 'value',
                        name: 'Proportion(%)',
                        position: 'right',
                        nameTextStyle: {
                            fontSize: '0.14rem',
                            fontWeight: 'bold'
                        },
                        axisLine: {
                            show: false
                        },
                        axisTick: {
                            show: true
                        },
                        axisLabel: {
                            formatter: function (value) {
                                return value + '%';
                            },
                            textStyle: {
                                fontSize: '0.14rem'
                            },
                            show: true
                        },
                        splitLine: {
                            show: false
                        }
                    }
                ],
                series: [
                    {
                        name: 'DefectQty',
                        type: 'bar',
                        itemStyle: {
                            normal: {
                                barBorderRadius: [10, 10, 0, 0],
                                color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [{
                                    offset: 0,
                                    color: "#009AFD"
                                }, {
                                    offset: 0.8,
                                    color: "#33DAFF"
                                }], false),
                                shadowColor: 'rgba(0, 0, 0, 0.1)',
                            }
                        },
                        data: DEFECT_QTY
                    },
                    {
                        name: 'Proportion',
                        type: 'line',
                        yAxisIndex: 1,
                        data: cumulativeYield,
                        itemStyle: {
                            color: '#FC8452',
                            Width: 2
                        },
                        itemStyle: { normal: { color: '#FC8452 ' } },
                        areaStyle: {
                            normal: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1,
                                    [
                                        { offset: 0, color: 'rgba(237, 178, 23, 0.5)' },
                                        { offset: 0.8, color: 'rgba(237, 178, 23, 0.1)' }
                                    ], false),
                                shadowColor: 'rgba(0, 0, 0, 0.1)',
                                shadowBlur: 1
                            }
                        },
                        tooltip: {
                            valueFormatter: function (value) {
                                return value + '%';
                            }
                        }
                    }
                ]
            };
            platoChar.setOption(option);
            if (platooptionloop) {
                //platooptionloop.clearLoop();
                platooptionloop = null;
            }
            platooptionloop = tools.loopShowTooltip(platoChar, option, { loopSeries: true });
        };
        var updatePlatoChart = function (product,process_id) {
            var filterData;
            if (process_id.toLowerCase() == "all") {
                filterData = Tab.Table3;
            }
            else {
                filterData = Tab.Table3.filter(function (item) {
                    return product.toLowerCase() === "all"
                        ? item.PROCESS === process_id
                        : item.COMPONENT === product && item.PROCESS === process_id;
                });
            }
            const group = {};
            filterData.forEach(item => {
                const defect = item.DEFECT;
                const qty = parseInt(item.DEFECT_QTY, 10);
                if (group[defect]) {
                    group[defect] += qty;
                } else {
                    group[defect] = qty;
                }
            });
            const chartData = Object.keys(group).map(defect => ({
                DEFECT: defect,
                DEFECT_QTY: group[defect]
            }));
            var DEFECTs = chartData.map(item => item.DEFECT);
            var DEFECT_QTY = chartData.map(item => parseFloat(item.DEFECT_QTY));
            var totalDefect_QTY = DEFECT_QTY.reduce((a, b) => a + b, 0);
            var cumulativeYield = [];
            var cumulativeSum = 0;
            DEFECT_QTY.forEach(function (value) {
                cumulativeSum += value;
                cumulativeYield.push(parseFloat((cumulativeSum / totalDefect_QTY * 100).toFixed(2)));
            });
            var itemcolor = [];
            var option = {
                xAxis: {
                    type: 'category',
                    data: DEFECTs,
                    axisLabel: {
                        interval: DEFECTs.length >= 50 ? Math.ceil(DEFECTs.length / 50) : 0,
                        rotate: 45
                    }
                },
                series: [
                    {
                        name: 'DefectQty',
                        data: DEFECT_QTY,
                        itemStyle: {
                            normal: {
                                barBorderRadius: [10, 10, 0, 0],
                                color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [{
                                    offset: 0,
                                    color: "#009AFD"
                                }, {
                                    offset: 0.8,
                                    color: "#33DAFF"
                                }], false),
                                shadowColor: 'rgba(0, 0, 0, 0.1)',
                            }
                        }
                    },
                    {
                        name: 'Proportion',
                        data: cumulativeYield
                    }
                ]
            };
            platoChar.setOption(option);
        };

        //updateChart
        var updateTabChart = function (fun, actionname) {
            var defect = $('#defect_input').val();
            var cl_type = $('#cmb_data_type').val();
            if (!fun) return;
            var chartdata;
            var dataZoomConfig = [];
            const actionMap = {
                defectByProcess: {
                    day: JSON.parse(Tab.Table4[0].DEFECT_RATIO_DAY_JSON),
                    week: JSON.parse(Tab.Table4[0].DEFECT_RATIO_WEEK_JSON),
                    month: JSON.parse(Tab.Table4[0].DEFECT_RATIO_MONTH_JSON),
                    updateFunc: updatedefectByProcessChartOptions
                },
                totalDefect: {
                    day: JSON.parse(Tab.Table5[0].TOTAL_DEFECT_DAY_JSON),
                    week: JSON.parse(Tab.Table5[0].TOTAL_DEFECT_WEEK_JSON),
                    month: JSON.parse(Tab.Table5[0].TOTAL_DEFECT_MONTH_JSON),
                    updateFunc: updatetotalDefectChartOptions
                },
                defectByFailureMode: {
                    day: JSON.parse(Tab.Table6[0].FAILURE_MODE_DAY_JSON),
                    week: JSON.parse(Tab.Table6[0].FAILURE_MODE_WEEK_JSON),
                    month: JSON.parse(Tab.Table6[0].FAILURE_MODE_MONTH_JSON),
                    updateFunc: updatedefectByFailureModeChartOptions
                }
            };
            const commonDataZoomConfig = [
                {
                    type: 'inside',
                    start: 0,
                    end: 100,
                    xAxisIndex: [0, 1]
                },
                {
                    type: 'slider',
                    start: 0,
                    end: 100,
                    xAxisIndex: [0, 1],
                    handleSize: 0,
                    height: "0.3rem",
                    show: false,
                    zoomOnMouseWheel: true
                }
            ];
            for (let key in actionMap) {
                if (actionname == key) {
                    const actionConfig = actionMap[key];
                    chartdata = actionConfig[cl_type.toLowerCase()];
                    if (cl_type.toLowerCase() === 'day') {
                        dataZoomConfig = commonDataZoomConfig;
                    }
                    if (cl_type.toLowerCase() === 'month') {
                        updatePlatoChart('ALL','ALL');
                    }
                    if (actionname !== "Yield" && defect !== "ALL") {
                        chartdata = chartdata.filter(item => item.PROCESS == defect);
                    }
                    actionConfig.updateFunc(chartdata, dataZoomConfig);
                    break;
                }
            }
        };

        //defect下拉月周日页签联动
        $('#cmb_data_type,#defect_input').on('change', function () {
            var i, tablinks,fun, action;
            tablinks = document.getElementsByClassName("tab")[0].getElementsByClassName("tablinks");
            for (i = 0; i < tablinks.length; i++) {
                if (tablinks[i].className.includes("active")) {
                    switch (i) {
                        case 0:
                            action = "totalDefect";
                            fun = totalDefectChar;
                            break;
                        case 1:
                            action = "defectByProcess";
                            fun = defectByProcessChar;
                            break;
                        case 2:
                            action = "defectByFailureMode";
                            fun = defectByFailureModeChart;
                            break;
                    }
                }
            }
            updateTabChart(fun,action);
            updatePlatoChart( $('#cmb_product_code').val(), $('#defect_input').val());
        });
        //报表点击联动
        var process_select = function (product,process_id) {
            if (totalDefectChar) {
               tablinksonclick("defectByProcess");
               $(".search").css("display", "block");
               $('#defect_input').val(process_id);
               var chartDom = document.getElementById("charttab1");
               if (chartDom) {
                   echarts.dispose(chartDom);
               }
               defectByProcessChar = echarts.init(chartDom);
               var chartData = JSON.parse(Tab.Table4[0].DEFECT_RATIO_DAY_JSON);
               const filterData = chartData.filter(item => item.PROCESS === process_id);
               updatedefectByProcessChartOptions(filterData, null);
            }
            if (platoChar) {
                updatePlatoChart(product, process_id);
            }
        };
        window.addEventListener('resize', function () {
            [totalDefectChar, defectByProcessChar, platoChar].forEach(function (chart) {
                if (chart) {
                    setTimeout(chart.resize.bind(chart), 750);
                }
            });
        });
    </script>
</body>
</html>